import matplotlib.pyplot as plt
import numpy as np
import sympy as sp

import math
from itertools import permutations, combinations
from scipy import stats



def set_chinese_font():
    """设置中文字体"""
    plt.rcParams['font.sans-serif'] = ['SimHei', 'Microsoft YaHei', 'DejaVu Sans']
    plt.rcParams['axes.unicode_minus'] = False  # 解决负号显示问题

set_chinese_font()

def sequences_and_induction():
    print("=== 数列与数学归纳法 ===")
    
    # 数学归纳法示例：证明 1 + 2 + 3 + ... + n = n(n+1)/2
    def sum_formula(n):
        """直接计算和"""
        return n * (n + 1) // 2
    
    def sum_sequential(n):
        """顺序计算和"""
        return sum(range(1, n + 1))
    
    # 验证基础情况
    print("数学归纳法验证:")
    print("基础情况 (n=1):")
    print(f"  左边: 1 = 1")
    print(f"  右边: 1×(1+1)/2 = {sum_formula(1)}")
    print(f"  验证: {1 == sum_formula(1)}")
    
    # 验证归纳步骤
    print("\n归纳步骤 (假设n=k成立，证明n=k+1成立):")
    k = 5  # 示例
    assumed_sum = sum_formula(k)  # 归纳假设
    next_sum_sequential = sum_sequential(k + 1)
    next_sum_formula = sum_formula(k + 1)
    
    print(f"  假设 1+2+...+{k} = {k}({k}+1)/2 = {assumed_sum}")
    print(f"  那么 1+2+...+{k}+{k+1} = {assumed_sum} + {k+1} = {assumed_sum + k + 1}")
    print(f"  公式计算: ({k+1})({k+1}+1)/2 = {next_sum_formula}")
    print(f"  验证: {assumed_sum + k + 1 == next_sum_formula}")
    
    # 数列极限
    def sequence_convergence(sequence_func, n_terms=20):
        """研究数列的收敛性"""
        terms = [sequence_func(n) for n in range(1, n_terms + 1)]
        return terms
    
    # 收敛数列示例: a_n = 1 + 1/n
    convergent_seq = sequence_convergence(lambda n: 1 + 1/n)
    
    # 发散数列示例: a_n = n
    divergent_seq = sequence_convergence(lambda n: n)
    
    # 可视化
    plt.figure(figsize=(12, 5))
    
    plt.subplot(1, 2, 1)
    plt.plot(range(1, 21), convergent_seq, 'bo-', label='aₙ = 1 + 1/n')
    plt.axhline(y=1, color='r', linestyle='--', label='极限值 = 1')
    plt.title('收敛数列')
    plt.xlabel('n')
    plt.ylabel('aₙ')
    plt.grid(True)
    plt.legend()
    
    plt.subplot(1, 2, 2)
    plt.plot(range(1, 21), divergent_seq, 'ro-', label='aₙ = n')
    plt.title('发散数列')
    plt.xlabel('n')
    plt.ylabel('aₙ')
    plt.grid(True)
    plt.legend()
    
    plt.tight_layout()
    plt.show()
    
    # 验证多个n值
    print(f"\n公式验证 (前10个自然数):")
    for n in range(1, 11):
        formula_result = sum_formula(n)
        sequential_result = sum_sequential(n)
        print(f"  n={n}: 公式={formula_result}, 计算={sequential_result}, 正确={formula_result == sequential_result}")

sequences_and_induction()


